package com.baorant.springdemo1.controller;

import com.baorant.springdemo1.domain.User;
import com.baorant.springdemo1.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

@RequestMapping("/user")
@RestController
public class UserController {
    private final UserService userService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/insertUser")
    public ResponseEntity<User> createUser(@RequestParam String name, @RequestParam String password) {
        User user = userService.createUser(name, passwordEncoder.encode(password));
        return ResponseEntity.ok(user);
    }

    @GetMapping("/search")
    public ResponseEntity<User> findUsersByName(@RequestParam String name) {
        User users = userService.findUsersByName(name);
        return ResponseEntity.ok(users);
    }

    @RequestMapping("/getUser")
    public User getUser() {
        User user = new User();
        user.setAge(18);
        user.setName("baorant");
        user.setPassword("hello");
        return user;
    }

    @PostMapping("/login")
    public ResponseEntity<String> userLogin(@RequestParam String name, @RequestParam String password) {
        User users = userService.findUsersByName(name);
        if (users.getPassword().equals(password)) {
            return ResponseEntity.ok("success");
        }
        return ResponseEntity.ok("fail");
    }

    @GetMapping("/hello2")
    public String hello() {
        return "hello";
    }

    @PostMapping("/register")
    public ModelAndView userRegister(@RequestParam String name, @RequestParam String password) {
        ModelAndView mav = new ModelAndView();

        User users = userService.createUser(name, passwordEncoder.encode(password));
        if (users != null) {
            mav.setViewName("login");
            return mav;
        }
        mav.setViewName("register");  // 视图名
        return mav;
    }
}
